﻿using Dubbo.Common.DynamicProxy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Dubbo.Rpc
{
    public class InvokerInvocationHandler<T> : IInvocationHandler
    {
        private readonly IInvoker<T> invoker;

        public InvokerInvocationHandler(IInvoker<T> handler)
        {
            this.invoker = handler;
        }

        public object Invoke(object proxy, MethodInfo method, object[] args)
        {
            string methodName = method.Name;
            var parameters = method.GetParameters();
            if (method.DeclaringType == typeof(object))
            {
                return method.Invoke(invoker, args);
            }
            if ("ToString" == methodName && parameters.Length == 0)
            {
                return invoker.ToString();
            }
            if ("GetHashCode" == methodName && parameters.Length == 0)
            {
                return invoker.GetHashCode();
            }
            if ("Equals" == methodName && parameters.Length == 1)
            {
                return invoker.Equals(args[0]);
            }
            return invoker.Invoke(new RpcInvocation<T>(method, args)).recreate();
        }
    }
}
